package org.opencare.plugins.gdacs;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;

public class GDACStoEDXLTransformer implements OpenCARETransformer, ApplicationContextAware {

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());
	
	private String styleSheetTarget;
	private ApplicationContext applicationContext;
	
	public void setStyleSheetTarget(String styleSheetTarget) {
		 this.styleSheetTarget = styleSheetTarget;
	}

	public String transform(String xml) throws MalformedURLException, TransformerException {
		// TODO Auto-generated method stub
		OutputStream resultStream = new ByteArrayOutputStream();
		Resource rs = applicationContext.getResource(styleSheetTarget);
		String abXSL = null;
		
		try {
			abXSL = rs.getFile().getAbsolutePath();
			logger.debug(abXSL);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
				
		Reader xmlReader = new StringReader(xml);
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer;
		transformer = tFactory.newTransformer(new StreamSource(abXSL));
		transformer.transform(new StreamSource(xmlReader), new StreamResult(
				resultStream));

		return resultStream.toString();
	}

	@Override
	public void setApplicationContext(ApplicationContext ac)
			throws BeansException {
		// TODO Auto-generated method stub
		this.applicationContext = ac;

	}
}
